package com.hzlx.web;

import com.alibaba.fastjson2.JSON;
import com.hzlx.dto.InventoryResponse;
import com.hzlx.dto.ProductRequest;

import com.hzlx.dto.ProductResponse;
import com.hzlx.dto.ResultDto;
import com.hzlx.service.ProductService;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.fasterxml.jackson.databind.type.LogicalType.Map;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/product")
@Slf4j
public class ProductController {
    @Resource
    RestTemplate restTemplate;
    @Resource
    private final ProductService productService;
    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public void create(@RequestBody ProductRequest productRequest){

        productService.create(productRequest);
        log.info("创建成功："+productRequest.toString());
    }
    @GetMapping
    @ResponseStatus(HttpStatus.OK)
    public ResultDto<List<ProductResponse>> findAll(){
        List<ProductResponse> list = productService.findAll();
        //远程调用查库存
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        List<java.util.Map<String,Object>> skus=list.stream().map(resp->resp.getSku()).collect(Collectors.toList());
        HttpEntity entity = new HttpEntity<>(skus, headers);
        ParameterizedTypeReference<ResultDto<List<InventoryResponse>>> pt = new ParameterizedTypeReference<>() {};
        ResponseEntity<ResultDto<List<InventoryResponse>>> result =
                restTemplate.exchange("http://inventory-service/api/inventory/isInStock",
                        HttpMethod.POST,
                        entity,
                        pt);
        if (result.getStatusCode().is2xxSuccessful() && result.getBody().getCode().equals("ok")){
             List<InventoryResponse> inventoryResponses = result.getBody().getData();
             list.stream().forEach(product->{
                 String sku = JSON.toJSONString(product.getSku());
                 Integer stock = inventoryResponses.stream()
                         .filter(inventory->inventory.getSku().equals(sku))
                         .map(inventory->inventory.getQuantity())
                         .findFirst().orElseGet(()->0);
                 product.setStock(stock);
             });

        }
        return ResultDto.<List<ProductResponse>>builder()
                .code("ok")
                .data(list)
                .build();
    }
    @PostMapping("/delete")
    public void delete(String id){
        productService.delete(id);
    }
}
